<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="省" prop="provinceId">
                <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" :disabled="isAdminShows"
                    clearable>
                    <!-- <el-option v-if="isAdminShow" key="" label="全国" value=""></el-option> -->
                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市" prop="cityId">
                <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区/县" prop="prefectureId">
                <el-select v-model="queryParams.prefectureId" placeholder="请选择区/县" clearable>
                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="结构类型" prop="structureType">
                <el-select v-model="queryParams.structureType" placeholder="请选择结构类型" clearable>
                    <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="设防烈度" prop="intensity">
                <el-select v-model="queryParams.intensity" placeholder="请选择设防烈度" clearable @focus="intensityFocus">
                    <el-option v-for="item in option1" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAdd">添加</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" @click="handleImport1">批量导入</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" border :span-method="objectSpanMethod">
            <el-table-column label="省" align="center" prop="province" />
            <el-table-column label="市" align="center" prop="city" />
            <el-table-column label="区（县）" align="center" prop="prefecture" />
            <el-table-column label="结构类型" align="center" prop="structureType">
                <template #default="scope">
                    <span v-if="scope.row.structureType == '0'">高层建筑</span>
                    <span v-else-if="scope.row.structureType == '1'">钢结构</span>
                    <span v-else-if="scope.row.structureType == '2'">多层钢筋混凝土结构</span>
                    <span v-else-if="scope.row.structureType == '3'">砖混结构</span>
                    <span v-else-if="scope.row.structureType == '4'">砖木结构</span>
                    <span v-else-if="scope.row.structureType == '5'">土结构</span>
                    <span v-else-if="scope.row.structureType == '6'">木结构</span>
                    <span v-else-if="scope.row.structureType == '7'">石结构</span>
                    <span v-else-if="scope.row.structureType == '8'">其他结构</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="设防烈度" align="center" prop="intensity" /> -->
            <el-table-column label="破坏程度" align="center" prop="destroy">
                <template #default="scope">
                    <span v-if="scope.row?.destroy == '0'">基本完好</span>
                    <span v-else-if="scope.row?.destroy == '1'">轻微破坏</span>
                    <span v-else-if="scope.row?.destroy == '2'">中等破坏</span>
                    <span v-else-if="scope.row?.destroy == '3'">严重破坏</span>
                    <span v-else-if="scope.row?.destroy == '4'">毁坏</span>
                </template>
            </el-table-column>
            <el-table-column label="地震烈度" align="center">
                <el-table-column label="VI(0.05g)" align="center" prop="six"></el-table-column>
                <el-table-column label="VII(0.10g)" align="center" prop="seven"></el-table-column>
                <el-table-column label="VIII(0.20g)" align="center" prop="eight"></el-table-column>
                <el-table-column label="IX(0.40g)" align="center" prop="nine"></el-table-column>
                <el-table-column label="X(0.80g)" align="center" prop="ten"></el-table-column>
            </el-table-column>
            <el-table-column label="操作" align="center" prop="structureType" class-name="small-padding fixed-width"
                >
                <!-- v-if="isAdminShows" -->
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修改弹出框 -->
        <el-dialog :title="title" v-model="open" append-to-body width="1200px">
            <p class="dialogTitle">{{ title }}</p>
            <el-form ref="buildVulnerabilityRef" :model="form" :rules="rules" style="padding:0 40px 0px 20px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="省" prop="provinceId" label-width="150px">
                            <el-select v-model="form.provinceId" placeholder="请选择省" @change="chooseProvince" clearable
                                :disabled="isUpdate">
                                <el-option v-for="item in form.provinceDatas" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市" prop="cityId" label-width="150px">
                            <el-select v-model="form.cityId" placeholder="请选择市" @change="chooseCity" clearable
                                :disabled="isUpdate">
                                <el-option v-for="item in form.cityDatas" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区（县）" prop="prefectureId" label-width="150px">
                            <el-select v-model="form.prefectureId" placeholder="请选择区（县）" clearable :disabled="isUpdate">
                                <el-option v-for="item in form.prefectureDatas" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="结构类型" prop="structureType" label-width="150px">
                            <el-select v-model="form.structureType" placeholder="请选择结构类型" clearable :disabled="isUpdate">
                                <el-option v-for="item in option" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="设防烈度" prop="intensity" label-width="150px">
                            <el-select v-model="form.intensity" placeholder="请选择设防烈度" clearable :disabled="isUpdate">
                                <el-option v-for="item in option1" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-table :data="form.dataDetailList" border :span-method="objectSpanMethod" class="borderTable">
                    <el-table-column label="破坏程度" align="center" prop="destroy">
                        <template #default="scope">
                            <span v-if="scope.row?.destroy == '0'">基本完好</span>
                            <span v-else-if="scope.row?.destroy == '1'">轻微破坏</span>
                            <span v-else-if="scope.row?.destroy == '2'">中等破坏</span>
                            <span v-else-if="scope.row?.destroy == '3'">严重破坏</span>
                            <span v-else-if="scope.row?.destroy == '4'">毁坏</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="地震烈度" align="center">
                        <el-table-column label="VI(0.05g)" align="center" prop="six">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.six'" :rules="rules.six">
                                    <el-input v-model="scope.row.six" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="VII(0.10g)" align="center" prop="seven">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.seven'" :rules="rules.seven">
                                    <el-input v-model="scope.row.seven" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="VIII(0.20g)" align="center" prop="eight">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.eight'" :rules="rules.eight">
                                    <el-input v-model="scope.row.eight" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="IX(0.40g)" align="center" prop="nine">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.nine'" :rules="rules.nine">
                                    <el-input v-model="scope.row.nine" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="X(0.80g)" align="center" prop="ten">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.ten'" :rules="rules.ten">
                                    <el-input v-model="scope.row.ten" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" :isDisabled="isDisabled">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body custom-class="dialogTable">
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('建筑物易损性导入数据模板.xlsx')">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm" :isDisabled="isDisabled">确 定</el-button>
                    <el-button plain @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 批量导入弹出框 -->
        <el-dialog :title="title1" v-model="open1" append-to-body width="1200px">
            <p class="dialogTitle">{{ title1 }}</p>
            <el-form ref="buildVulnerabilityRef1" :model="form1" :rules="rules" style="padding:0 40px 0px 20px">
                <el-row>
                    <el-col>
                        <el-form-item label="更新地区">
                            <el-radio-group v-model="radio" @change="changeAre">
                                <el-radio label="按行政区选择">按行政区选择</el-radio>
                                <el-radio label="按设防烈度选择">按设防烈度选择</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <template v-if="radio == '按行政区选择'">
                        <el-col :span="12">
                            <el-form-item label="行政区" prop="xzq">
                                <el-cascader v-model="form1.xzq" :options="options" :props="props" placeholder="请选择" class="cascaderClass"
                                    separator="-" collapse-tags collapse-tags-tooltip clearable ref="xzqRef" @change="changeXzq" />
                                <!-- <el-cascader v-model="form1.xzq" :props="props" clearable separator="-"
                                  collapse-tags collapse-tags-tooltip ref="xzqRef" @change="changeXzq" :options="options">
                                </el-cascader> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结构类型" prop="structureType">
                                <el-select v-model="form1.structureType" placeholder="请选择结构类型" clearable>
                                    <el-option v-for="item in option" :key="item.value" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <template v-else>
                        <el-col :span="8">
                            <el-form-item label="设防烈度" prop="intensity">
                                <el-select v-model="form1.intensity" placeholder="请选择设防烈度" clearable
                                    @change="changeIntensity">
                                    <el-option v-for="item in option1" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="省" prop="province">
                                <el-select v-model="form1.province" multiple collapse-tags collapse-tags-tooltip placeholder="请选择省" @change="changeProvince" clearable>
                                    <el-option v-for="(item,index) in form1.provinceDatas" :label="item.province"
                                        :value="item.province" :key="index"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="市" prop="cityIds">
                                <el-select v-model="form1.city" multiple collapse-tags collapse-tags-tooltip placeholder="请选择市" @change="changeCity" clearable>
                                    <el-option v-for="(item,index) in form1.cityDatas" :label="item.city"
                                        :value="item.city" :key="index"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="结构类型" prop="structureType">
                                <el-select v-model="form1.structureType" placeholder="请选择结构类型" clearable>
                                    <el-option v-for="item in option" :key="item.value" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>
                <el-row style="margin-bottom: 10px!important;color: var(--el-color-primary);">
                    <el-col :span="21">
                        <el-tooltip class="box-item" effect="light" :content="newSelectionArea" placement="bottom">
                            <span v-if="newSelectionArea != ''" class="ellipsis">已选择地区：{{ newSelectionArea }}</span>
                        </el-tooltip>
                        <span v-if="newSelectionArea == ''"></span>
                    </el-col>
                    <el-col :span="3" style="text-align: right;">
                        <span @click="handleImport" style="cursor: pointer;">导入矩阵</span>
                    </el-col>
                </el-row>

                <el-table :data="form1.dataDetailList" border :span-method="objectSpanMethod" class="borderTable">
                    <el-table-column label="破坏程度" align="center" prop="destroy">
                        <template #default="scope">
                            <span v-if="scope.row.destroy == '0'">基本完好</span>
                            <span v-else-if="scope.row.destroy == '1'">轻微破坏</span>
                            <span v-else-if="scope.row.destroy == '2'">中等破坏</span>
                            <span v-else-if="scope.row.destroy == '3'">严重破坏</span>
                            <span v-else-if="scope.row.destroy == '4'">毁坏</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="地震烈度" align="center">
                        <el-table-column label="VI(0.05g)" align="center" prop="six">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.six'" :rules="rules.six">
                                    <el-input v-model="scope.row.six" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="VII(0.10g)" align="center" prop="seven">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.seven'" :rules="rules.seven">
                                    <el-input v-model="scope.row.seven" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="VIII(0.20g)" align="center" prop="eight">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.eight'" :rules="rules.eight">
                                    <el-input v-model="scope.row.eight" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="IX(0.40g)" align="center" prop="nine">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.nine'" :rules="rules.nine">
                                    <el-input v-model="scope.row.nine" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="X(0.80g)" align="center" prop="ten">
                            <template #default="scope">
                                <el-form-item :prop="'dataDetailList.' + scope.$index + '.ten'" :rules="rules.ten">
                                    <el-input v-model="scope.row.ten" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm1" :isDisabled="isDisabled">确定</el-button>
                    <el-button plain @click="open1 = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="buildVulnerability">
import { getProvince, getChildArea } from "@/api/system/division";
import { ElMessage } from 'element-plus'
import { getAllbuildingVulnerability, saveBuildingVulnerability, updatebuildingVulnerability, getPermission, delbuildingVulnerability, getbuildingVulnerability, getBySfIntensity, bashSave } from "@/api/basedatamanage/buildVulnerability.js"
import { getLanderRoles } from "@/api/basedatamanage/common.js"
import { getToken } from "@/utils/auth";
import { dataMethod } from './spanTable.js'
const { proxy } = getCurrentInstance();
const ids = ref();
const dataList = ref([]);
const spanObj = ref();
const spanObjUpdate = ref();
const loading = ref(false);
const open = ref(false);
const title = ref("");
const showSearch = ref(true);
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县
const messageArr = ref([]);
const isUpdate = ref(false);
const isAdmin = ref(true);
const isDisabled = ref(false);
/*** 用户导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "tokrn " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/buildingVulnerability/importVulnerability"
});
const option = [{ value: '0', label: '高层建筑' }, { value: '1', label: '钢结构' }, { value: '2', label: '多层钢筋混凝土结构' }, { value: '3', label: '砖混结构' }, { value: '4', label: '砖木结构' }, { value: '5', label: '土结构' }, { value: '6', label: '木结构' }, { value: '7', label: '石结构' }, { value: '8', label: '其他结构' }];
const option1 = ref([{ label: '6度', value: '6度' }, { label: '7度', value: '7度' }, { label: '8度', value: '8度' }, { label: '9度', value: '9度' }, { label: '未设防', value: '未设防' }]);
// 保留两位小数
const positive2decimals = (rule, value, callback) => {
    if (value) {
        value = String(value)
    }
    if (!value) {
        callback(new Error())
    } else if (value.split('.').length > 2) {
        callback(new Error()) //防止输入多个小数点
    } else {
        value = Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2) //四舍五入
        value = Number(value).toFixed(2); //不足补位
        // this.traditionDetails.orderPrice = value;
        if (open.value) {
            if (rule.field.split('.')[2] == 'six') {
                form.value.dataDetailList[rule.field.split('.')[1]].six = value;
            } else if (rule.field.split('.')[2] == 'seven') {
                form.value.dataDetailList[rule.field.split('.')[1]].seven = value;
            } else if (rule.field.split('.')[2] == 'eight') {
                form.value.dataDetailList[rule.field.split('.')[1]].eight = value;
            } else if (rule.field.split('.')[2] == 'nine') {
                form.value.dataDetailList[rule.field.split('.')[1]].nine = value;
            } else {
                form.value.dataDetailList[rule.field.split('.')[1]].ten = value;
            }
        } else if (open1.value) {
            if (rule.field.split('.')[2] == 'six') {
                form1.value.dataDetailList[rule.field.split('.')[1]].six = value;
            } else if (rule.field.split('.')[2] == 'seven') {
                form1.value.dataDetailList[rule.field.split('.')[1]].seven = value;
            } else if (rule.field.split('.')[2] == 'eight') {
                form1.value.dataDetailList[rule.field.split('.')[1]].eight = value;
            } else if (rule.field.split('.')[2] == 'nine') {
                form1.value.dataDetailList[rule.field.split('.')[1]].nine = value;
            } else {
                form1.value.dataDetailList[rule.field.split('.')[1]].ten = value;
            }
        }

        callback();
    }
}
const data = reactive({
    queryParams: {
        provinceId: '',
        cityId: '',
        prefectureId: '',
        structureType: '',
        // intensity: '',
    },
    form: {
        provinceId: undefined,
        cityId: undefined,
        prefectureId: undefined,
        structureType: undefined,
        // intensity: undefined,
        dataDetailList: [],
        provinceDatas: undefined,
        cityDatas: undefined,
        prefectureDatas: undefined,
    },
    form1: {
        province:[],
        xzq: undefined,
        provinceId: undefined,
        cityId: undefined,
        city: [],
        provinceDatas: undefined,
        cityDatas: undefined,
        intensity: '',
        structureType: undefined,
        dataDetailList: [],
    },
    rules: {
        provinceId: [{ required: true, message: '请选择省', trigger: 'change' }],
        cityId: [{ required: true, message: '请选择市', trigger: 'change' }],
        province: [{ required: true, message: '请选择省', trigger: 'change' }],
        prefectureId: [{ required: true, message: '请选择区（县）', trigger: 'change' }],
        xzq: [{ required: true, message: '请选择行政区', trigger: 'change' }],
        structureType: [{ required: true, message: '请选择结构类型', trigger: 'change' }],
        intensity: [{ required: true, message: '请选择设防烈度', trigger: 'change' }],
        six: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        seven: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        eight: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        nine: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
        ten: [{ required: false, message: '请输入保留两位小数的值', trigger: 'blur', validator: positive2decimals }],
    }
})
const { queryParams, form, form1, rules } = toRefs(data)


/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    queryParams.value.structureType = ''
    queryParams.value.page = 1;
    getPermissionData();
}

// 重置表单
function reset() {
    form.value = {
        provinceId: undefined,
        cityId: undefined,
        prefectureId: undefined,
        structureType: undefined,
        // intensity: undefined,
        dataDetailList: [],
        provinceDatas: undefined,
        cityDatas: undefined,
        prefectureDatas: undefined,
    }
    proxy.resetForm("buildVulnerabilityRef");
}


/** 查询建筑物易损性数据列表 */
function getList() {
    loading.value = true;
    getAllbuildingVulnerability(queryParams.value).then(response => {
        dataList.value = response.data;
        loading.value = false;
        spanObj.value = dataMethod(dataList.value, ['province', 'city', 'prefecture', 'structureType']);
        spanObjUpdate.value = [];
        for (let i = 0; i < dataList.value.length; i++) {
            if (i == 0 || i % 5 == 0) {
                spanObjUpdate.value.push(5);
            } else {
                spanObjUpdate.value.push(0);
            }
        }
        spanObj.value.updataObj = spanObjUpdate.value
        //    spanObj.value.intensity = spanObjUpdate.value
    });
}
// 合并列
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //判断合并列
    if (columnIndex == 11 && isAdmin.value) {
        const _row = spanObj.value['updataObj'] ? spanObj.value['updataObj'][rowIndex] : 1;
        const _col = _row > 0 ? 1 : 0;
        return {
            rowspan: _row,
            colspan: _col,
        }
    } else {
        const _row = spanObj.value[column.property] ? spanObj.value[column.property][rowIndex] : 1;
        const _col = _row > 0 ? 1 : 0;
        return {
            rowspan: _row,
            colspan: _col,
        }
    }
}

// 新增
function handleAdd() {
    reset();
    title.value = '添加建筑物易损性数据'
    getProvinceFormData();
    isUpdate.value = false;
    open.value = true;
    let arr = [{ destroy: '0' }, { destroy: '1' }, { destroy: '2' }, { destroy: '3' }, { destroy: '4' }];
    arr.forEach(item => {
        item.six = '';
        item.seven = '';
        item.eight = '';
        item.nine = '';
        item.ten = '';
    })
    form.value.dataDetailList = arr
}

// 修改
function handleUpdate(row) {
    reset();
    isUpdate.value = true;
    title.value = "修改建筑物易损性数据"
    getDetail(row)
}

function intensityFocus() {
    if (!queryParams.value.structureType) {
        proxy.$modal.msgWarning('请先选择结构类型！')
    }
}

/** 删除按钮操作 */
function handleDelete(row) {
    isUpdate.value = false;
    getDetail(row)
}

function getDetail(row) {
    const query = {
        province: row.province,
        city: row.city,
        prefecture: row.prefecture,
        structureType: row.structureType,
        // intensity:row.intensity,
    }
    getbuildingVulnerability(query).then(response => {
        form.value.structureType = row.structureType;
        // form.value.intensity = row.intensity;
        form.value.dataDetailList = response.data;
        if (isUpdate.value) {
            editProvinceFormData(response.data[0].provinceId, response.data[0].cityId)
            form.value.provinceId = response.data[0].provinceId;
            form.value.cityId = response.data[0].cityId;
            form.value.prefectureId = response.data[0].prefectureId;
        } else {
            let arrId = [];
            form.value.dataDetailList.forEach(item => {
                arrId.push(item.id);
            })
            ids.value = arrId.join(',')
            proxy.$modal.confirm('是否确认删除该建筑物易损性的数据项？').then(function () {
                return delbuildingVulnerability(ids.value);
            }).then((res) => {
                getList();
                proxy.$modal.msgSuccess('删除成功');
            }).catch(() => { });
        }
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["buildVulnerabilityRef"].validate(valid => {
        if (valid) {
            checkradio();
            if (messageArr.value.length > 0) {
                const msg = messageArr.value.join('<br/><br/>')
                ElMessage({
                    message: msg,
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                })
            } else {
                if (title.value == '添加建筑物易损性数据') {
                    form.value.dataDetailList.forEach(item => {
                        item.provinceId = form.value.provinceId;
                        item.cityId = form.value.cityId;
                        item.prefectureId = form.value.prefectureId;
                        item.structureType = form.value.structureType;
                        // item.intensity = form.value.intensity;
                    })
                    isDisabled.value = true;
                    saveBuildingVulnerability(form.value.dataDetailList).then(response => {
                        proxy.$modal.msgSuccess("保存成功");
                        open.value = false;
                        isDisabled.value = false;
                        getList();
                    }).catch(err=>{isDisabled.value = false;});
                } else {
                    isDisabled.value = true;
                    updatebuildingVulnerability(form.value.dataDetailList).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        isDisabled.value = false;
                        getList();
                    }).catch(err=>{isDisabled.value = false;});
                }
            }
        }
    });

}

// 防止精度不准确
function precision(num, precise) {
    return parseFloat(num.toPrecision(precise));
}

// 校验表单项目比例
function checkradio() {
    messageArr.value = [];
    var six = 0;
    var seven = 0;
    var eight = 0;
    var nine = 0;
    var ten = 0;
    if (open.value) {
        form.value.dataDetailList.forEach(item => {//遍历数据
            six += parseFloat(item.six)
            seven += parseFloat(item.seven)
            eight += parseFloat(item.eight)
            nine += parseFloat(item.nine)
            ten += parseFloat(item.ten)
        })
    } else if (open1.value) {
        form1.value.dataDetailList.forEach(item => {//遍历数据
            six += parseFloat(item.six)
            seven += parseFloat(item.seven)
            eight += parseFloat(item.eight)
            nine += parseFloat(item.nine)
            ten += parseFloat(item.ten)
        })
    }
    if (precision(six, 3) != 1.00) {
        messageArr.value.push('VI的破坏占比不为1')
    }
    if (precision(seven, 3) != 1.00) {
        messageArr.value.push('VII的破坏占比不为1')
    }
    if (precision(eight, 3) != 1.00) {
        messageArr.value.push('VIII的破坏占比不为1')
    }
    if (precision(nine, 3) != 1.00) {
        messageArr.value.push('IX的破坏占比不为1')
    }
    if (precision(ten, 3) != 1.00) {
        messageArr.value.push('X度的破坏占比不为1')
    }
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

// 模板下载
function importTemplate(name) {
    proxy.download("/base/product/downloadExcel", {
        fileName: name
    }, name);
};

/** 导出按钮操作 */
function handleExport() {
    proxy.download('buildingVulnerability/exportExcel', {
        ...queryParams.value
    }, `建筑物易损性数据${new Date().getTime()}.xls`)
}

/** 获取省列表 */
function getProvinceData() {
    getProvince().then(response => {
        provinceData.value = response.data;
        getPermissionData();
    });
}
function chooseProvince(value) {
    if (title.value == '添加建筑物易损性数据' && open.value) {
        form.value.cityId = null;
        form.value.prefectureId = null;
        form.value.cityDatas = [];
        form.value.prefectureDatas = [];
        getChildArea(value).then(response => {
            form.value.cityDatas = response.data;
        });
    }
    // else if (title1.value == '批量导入建筑物易损性数据' && open1.value) {
    //     form1.value.cityId = null;
    //     form1.value.cityDatas = [];
    //     getChildArea(value).then(response => {
    //         form1.value.cityDatas = response.data;
    //     });
    // } 
    else {
        if(!value){
            queryParams.value.cityId = null;
            queryParams.value.prefectureId = null;
            cityData.value = [];
            areaData.value = [];
        }else{
            queryParams.value.cityId = null;
            queryParams.value.prefectureId = null;
            cityData.value = [];
            areaData.value = [];
            getChildArea(value).then(response => {
            cityData.value = response.data;
        });
        }

    }
}

function chooseCity(value) {
    if (title.value == '添加建筑物易损性数据' && open.value) {
        form.value.prefectureId = null;
        form.value.prefectureDatas = [];
        getChildArea(value).then(response => {
            form.value.prefectureDatas = response.data;
        });
    } else {
        queryParams.value.prefectureId = null;
        areaData.value = [];
        getChildArea(value).then(response => {
            areaData.value = response.data;
        });
    }
}


function getProvinceFormData() {
    getProvince().then(response => {
        form.value.provinceDatas = response.data;
        // form1.value.provinceDatas = response.data;
    });
}

function editProvinceFormData(provinceId, cityId) {
    getProvince().then(response => {
        form.value.provinceDatas = response.data;
    });
    getChildArea(provinceId).then(response => {
        form.value.cityDatas = response.data;
    });
    getChildArea(cityId).then(response => {
        form.value.prefectureDatas = response.data;
    });
    open.value = true;
}

function getPermissionData() {
    getPermission().then(res => {
        isAdmin.value = res.data.isAdmin;
        // 如果是国家级人员
        if (res.data.provinceId == '') {
            queryParams.value.provinceId = provinceData.value[0].id;
        } else {
            queryParams.value.provinceId = res.data.provinceId;
        }
        getChildArea(queryParams.value.provinceId).then(response => {
            cityData.value = response.data;
            if (res.data.cityId == '') {
                queryParams.value.cityId = cityData.value[0].id;
            } else {
                queryParams.value.cityId = res.data.cityId;
            }
            getChildArea(queryParams.value.cityId).then(response => {
                areaData.value = response.data;
                queryParams.value.prefectureId = areaData.value[0].id;
                getList();
            })
        })
    });
}
// 批量导入
const title1 = ref('');
const radio = ref('按行政区选择');
const open1 = ref(false);
const selectionArea = ref(); // 可选地区
const newSelectionArea = ref(); // 已选地区
const xzqRef = ref();
const props = {
    multiple: true, 
    // lazy: true,
    // lazyLoad(node, resolve) {
    //     let level = node.level;
    //     if (!node.value) {
    //         getProvince().then(res => {
    //             const nodes = Array.from(res.data).map(item => ({
    //                 value: item.id,
    //                 label: `${item.name}`,
    //                 leaf: level >= 2
    //             }));
    //             resolve(nodes);
    //         })
    //     } else {
    //         getChildArea(node.data.value).then(res => {
    //             const nodes = Array.from(res.data).map(item => ({
    //                 value: item.id,
    //                 label: `${item.name}`,
    //                 leaf: level >= 2
    //             }));
    //             // 通过调用resolve将子节点数据返回，通知组件数据加载完成
    //             resolve(nodes);
    //         })
    //     }
    // }
};
const options = ref([]);

const loadAllData = () => {
    getProvince().then(provinces=>{
        const provinceOptions = provinces.data.map(province => {
          return {
            value: province.id,
            label: province.name,
            children: []
          };
        });
        // 加载每个省份的子区域
        provinceOptions.forEach(provinceOption => {
          getChildArea(provinceOption.value).then(areas => {
            provinceOption.children = areas.data.map(area => ({
              value: area.id,
              label: area.name,
              children: []
            }));
            // 加载每个子区域的县级数据
            provinceOption.children.forEach(childOption => {
                    getChildArea(childOption.value).then(counties => {
                        childOption.children = counties.data.map(county => ({
                            value: county.id,
                            label: county.name,
                        }));
                        options.value = provinceOptions;
                        console.log(options.value,'处理数据');
                    });
                });
          });
        });
    })
};

function reset1() {
    form1.value = {
        province: [],
        city: [],
        provinceDatas: [],
        cityDatas: [],
        intensity: '',
        structureType: undefined,
        dataDetailList: [],
    }
    selectionArea.value = '';
    newSelectionArea.value = '';
    if (proxy.$refs["buildVulnerabilityRef1"] != undefined) {
        proxy.$refs["buildVulnerabilityRef1"].resetFields();
    }
    let arr = [{ destroy: '0' }, { destroy: '1' }, { destroy: '2' }, { destroy: '3' }, { destroy: '4' }];
    arr.forEach(item => {
        item.six = '';
        item.seven = '';
        item.eight = '';
        item.nine = '';
        item.ten = '';
    })
    form1.value.dataDetailList = arr
}
function handleImport1() {
    title1.value = '批量导入建筑物易损性数据';
    // getProvinceFormData();
    open1.value = true;
    reset1();
}
// 改变地区
function changeAre() {
    reset1();
}
// 改变设防 获取地区
function changeIntensity(value) {
    form1.value.province = [];
    form1.value.city = [];
    newSelectionArea.value = '';
    if (value) {
        getBySfIntensity({ sfIntensity: value }).then(res => {
            form1.value.provinceDatas = res.data.provinces;
            form1.value.cityDatas = [];
            selectionArea.value = res.data.divinsions;
        }).catch(() => {
            form1.value.provinceDatas = [];
            form1.value.cityDatas = [];
            selectionArea.value = '';
        })
    } else {
        form1.value.provinceDatas = [];
        form1.value.cityDatas = [];
        selectionArea.value = '';
    }
}
// 改变省
function changeProvince(value) {
    form1.value.city = [];
    form1.value.cityDatas = [];
    if (value.length>0) {
        value.forEach(provinceValue => {
          form1.value.provinceDatas.forEach(item => {
            if (item.province === provinceValue) {
              if (item.cityList.length > 0) {
                item.cityList.forEach(val => {
                  form1.value.cityDatas.push({ city: val });
                });
              }
            }
          });
        });
        console.log(form1.value.cityDatas);
        
        newSelectionArea.value = selectionArea.value.split('、')
          .filter(item => value.some(provinceValue => item.includes(provinceValue)))
          .join('、');
        
    } else {
        form1.value.city = [];
        form1.value.cityDatas = [];
        newSelectionArea.value = '';
    }
}
// 改变市
function changeCity(value) {
    if (value.length>0) {
        newSelectionArea.value = selectionArea.value.split('、')
          .filter(item => value.some(v => item.includes('-' + v + '-')))
          .join('、');
    } else {
        changeProvince(form1.value.province)
        // newSelectionArea.value = selectionArea.value.split('、').filter(item => item.includes(form1.value.province)).join('、');
    }
}
// 按行政区
function changeXzq(value) {
    if (value) {
        let xzq = xzqRef.value.getCheckedNodes();
        xzq = xzq.filter(option => (option.level == 3 && option.text))
        let arr = []
        xzq.forEach((item, index) => {
            arr.push(item.text);
        });
        newSelectionArea.value = arr.join('、');
    } else {
        newSelectionArea.value = '';
    }
}
/** 提交按钮 */
function submitForm1() {
    proxy.$refs["buildVulnerabilityRef1"].validate(valid => {
        if (valid) {
            checkradio();
            if (messageArr.value.length > 0) {
                const msg = messageArr.value.join('<br/><br/>')
                ElMessage({
                    message: msg,
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                })
            } else {
                const query = {
                    structureType: form1.value.structureType,
                    dataList: form1.value.dataDetailList,
                    divisions: newSelectionArea.value
                }
                isDisabled.value = true;
                bashSave(query).then(response => {
                    proxy.$modal.msgSuccess("保存成功");
                    isDisabled.value = false;
                    form1.value.dataDetailList = []
                    if (proxy.$refs["buildVulnerabilityRef1"] != undefined) {
                        proxy.$refs["buildVulnerabilityRef1"].clearValidate();
                    }
                    let arr = [{ destroy: '0' }, { destroy: '1' }, { destroy: '2' }, { destroy: '3' }, { destroy: '4' }];
                    arr.forEach(item => {
                        item.six = '';
                        item.seven = '';
                        item.eight = '';
                        item.nine = '';
                        item.ten = '';
                    })
                    form1.value.dataDetailList = arr
                    // open1.value = false;
                    getList();
                }).catch(err=>{
                    isDisabled.value = false;
                });
            }
        }
    });

}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在导入文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("导入文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    if (response.code == 200) {
        form1.value.dataDetailList = response.data;
    } else {
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    }
};
// 权限
const isAdminShow = ref(false)
const isAdminShows = ref(false)
const isAdminHandler = () => {
    getLanderRoles().then(res => {
        let { code, data } = res
        if (code == 200) {
            const auth = data.split(',')
            if (auth.includes('国家业务员') && auth.length == 1) {
                isAdminShow.value = false
                isAdminShows.value = false
            }else  if (auth.includes('国家管理员') && auth.length == 1) {
                isAdminShow.value = true
                isAdminShows.value = false
            }  else {
                isAdminShow.value = true
                isAdminShows.value = true
            }

        }
    })
}
loadAllData();
getProvinceData();
isAdminHandler()
</script>
  

<style lang="scss" scoped>
:deep(.el-table) td.el-table__cell {
    border-bottom: 1px solid #ebeef5 !important;
    border-right: 1px solid #ebeef5 !important;
}

.el-dialog {
    :deep(.el-cascader){
        :deep(.el-input){
            :deep(.el-input__inner){
                min-height: 30px!important;
            }
        }
    }
    :deep(.el-table) tr {
        height: 65px !important;
    }

    td.el-table__cell .cell .el-form-item {
        padding-top: 10px;
    }
}
:deep(.el-cascader){
        :deep(.el-input){
            :deep(.el-input__inner){
                min-height: 30px!important;
            }
        }
    }
.ellipsis {
    display: inline-block;
    width: 100%;
    /* 单行文本溢出省略号 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>